package com.jerry.shop.controller;

import com.jerry.shop.bean.Category;
import com.jerry.shop.exception.SellException;
import com.jerry.shop.form.CategoryForm;
import com.jerry.shop.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 卖家类目
 */
@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    //类目列表
    @GetMapping("/list")
    public ModelAndView list(Map<String, Object> map) {
        List<Category> categoryList = categoryService.findAll();
        map.put("categoryList", categoryList);
        return new ModelAndView("category/list", map);
    }

    //展示
    @GetMapping("/addOrUpdateIndex")
    public ModelAndView addOrUpdateIndex(@RequestParam(value = "id", required = false) Integer id,
                              Map<String, Object> map) {
        if (id != null) {
            Category category = categoryService.findOne(id);
            map.put("category", category);
        }
        return new ModelAndView("category/addOrUpdate", map);
    }

    //保存/更新
    @PostMapping("/addOrUpdate")
    public ModelAndView addOrUpdate(@Valid CategoryForm form,
                                     BindingResult bindingResult,
                                     Map<String, Object> map) {
        //绑定错误跳转
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/seller/category/addOrUpdateIndex");
            return new ModelAndView("common/error", map);
        }

        Category category = new Category();
        try {
            if (form.getId() != null) {
                category.setId(form.getId());
            }
            category.setName(form.getName());
            category.setType(Integer.valueOf(form.getType()));
            categoryService.saveOrUpdate(category);
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/seller/category/addOrUpdateIndex");
            return new ModelAndView("common/error", map);
        }

        map.put("url", "/seller/category/list");
        return new ModelAndView("common/success", map);
    }

}
